package com.jc.redis.serialize.kryo;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.ByteBufferInput;
import com.esotericsoftware.kryo.io.ByteBufferOutput;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.jc.redis.serialize.ISerializer;

/**
 * Created by starmezhh on 16/7/25.
 */
public class KryoSerializer implements ISerializer {

    Kryo kryo;

    public KryoSerializer(Kryo kryo) {
        this.kryo = kryo;
    }


    public <T> byte[] serialize(T T) {
        Output output = new ByteBufferOutput(4096,4096);
        kryo.writeObject(output,T);
        byte[] bytes = output.toBytes();
        output.close();
        return bytes;
    }


    public <T> T deserialize(byte[] bytes, Class<T> tClass) {
        Input input = new ByteBufferInput(bytes);
        T object = kryo.readObject(input,tClass);
        input.close();
        return object;
    }
}
